package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserLoginMapper;
import com.heima.admin.service.AdUserLoginService;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-03
 */
@Service
public class AdUserLoginServiceImpl extends ServiceImpl<AdUserLoginMapper, AdUser> implements AdUserLoginService {

    @Autowired
    private AdUserLoginMapper adUserLoginMapper;

    @Override
    public ResponseResult login(AdUser dto) {
        //如果传入的用户名不为空或null
        if (StringUtils.isEmpty(dto.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据传入用户名查找用户
        AdUser adUser = adUserLoginMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名输出错误,请重试");
        }
        //获取用户的密码盐和密码,将传入的密码进行加密对比
        String salt = adUser.getSalt();
        String pswd = dto.getPassword();
        String password = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
        //如果对比失败,返回密码错误
        if (!adUser.getPassword().equals(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //如果成功对比,在请求中添加token
        //返回数据  jwt
        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        adUser.setSalt("");
        adUser.setPassword("");
        map.put("user", adUser);
        return ResponseResult.okResult(map);
    }
}
